#ifndef LOG_H
#define LOG_H

#include <iostream>
#include <string>
#include <list>
#include <thread>
#include <atomic>
#include <fstream>
#include "block_queue.h"

enum LogLevel
{
    Debug,    // 调试
    Info,     // 信息
    Warning,  // 警告
    Critical, // 关键
    Error     // 致命的
};

class Log
{
public:
    static Log *GetInstance()
    {
        static Log log;
        return &log;
    }

    // 路径，文件名称，输出等级，异步队列大小-默认为，单行最大字符，最大行数
    bool init(const std::string &log_path, const std::string &log_file_name,int level, int async_log_size = 0, int log_buf_size = 1024, int split_lines = 500000);
    void writeLog(const char *current_file_name, int line_number, LogLevel level, const char *format, ...);
    void flush();
    void asyncwritelog();

private:
    Log();
    ~Log();
    // 禁用特殊成员函数
    Log(const Log &) = delete;
    Log(Log &&) = delete;
    Log &operator=(const Log &) = delete;
    Log &operator=(Log &&) = delete;

private:
    std::string log_path_;      // 日志路径
    std::string log_file_name_; // 日志文件名
    int log_buf_size_;          // 日志缓冲区大小
    int split_lines_;           // 最大行数
    int count_line_;            // 当前行数
    int level_;                 //当前日志输出等级
    char *log_buf_;

    int log_day_;
    BlockQueue<std::string> *log_block_queue_; // 异步队列
    int async_log_size_;                       // 异步大小
    std::ofstream file_;
    std::thread async_thread_;
    std::atomic<bool> is_running_async_; // 异步写日志线程是否正在运行
    std::mutex mutex_;                   // 互斥锁，保护日志缓冲区
};

#define LOG_DEBUG(message, ...) Log::GetInstance()->writeLog(__FILE__, __LINE__, Debug, message, ##__VA_ARGS__)
#define LOG_INFO(message, ...) Log::GetInstance()->writeLog(__FILE__, __LINE__, Info, message, ##__VA_ARGS__)
#define LOG_WARING(message, ...) Log::GetInstance()->writeLog(__FILE__, __LINE__, Warning, message, ##__VA_ARGS__)
#define LOG_CRITICAL(message, ...) Log::GetInstance()->writeLog(__FILE__, __LINE__, Critical, message, ##__VA_ARGS__)
#define LOG_ERROR(message, ...) Log::GetInstance()->writeLog(__FILE__, __LINE__, Error, message, ##__VA_ARGS__)

#endif // LOG_H
